package top.lyc829.mymusic.ui.fragment.comment

import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.ToastUtils
import top.lyc829.mymusic.adapter.multi.comment.CommentBinder
import top.lyc829.mymusic.adapter.multi.comment.CommentTitleBinder
import top.lyc829.mymusic.base.BaseFragment
import top.lyc829.mymusic.databinding.FragmentCommentBinding
import top.lyc829.mymusic.model.bean.Comment
import java.util.ArrayList

class CommentFragment : BaseFragment<CommentViewModel, FragmentCommentBinding>() {
    companion object {
        fun newInstance() = CommentFragment()
        const val TAG = "CommentFragment"
    }

    override fun getViewModel() = ViewModelProvider(this).get(CommentViewModel::class.java)

    override fun getBinding(inflater: LayoutInflater) = FragmentCommentBinding.inflate(inflater)

    override fun initView(savedInstanceState: Bundle?) {
        mViewModel.adapter.run {
            addItemBinder(String::class.java, CommentTitleBinder())
            addItemBinder(Comment::class.java, CommentBinder())
        }

        binding.recycler.layoutManager = LinearLayoutManager(context)
        binding.recycler.adapter = mViewModel.adapter
    }

    override fun initClickListener() {

    }

    override fun createObserver() {
        mViewModel.hotComments.observe(viewLifecycleOwner) {
            mViewModel.adapter.addData(it)
        }

        mViewModel.comments.observe(viewLifecycleOwner) {
            if (mViewModel.pageInfo.page == 1) {
                mViewModel.adapter.addData("最新评论")
            }
            mViewModel.adapter.addData(it)
        }

        mViewModel.errorLiveData.observe(viewLifecycleOwner) {
            Log.d(TAG, it.toString())
            ToastUtils.showShort(it.errorMsg)
        }
    }

    override fun initData() {
        mViewModel.id = arguments?.getLong("id") ?: -1
        if (mViewModel.adapter.data.isEmpty()) {
            mViewModel.adapter.addData("热门评论")
        }
        mViewModel.getComments(mViewModel.id)
    }
}